package com.joinway.admin.platform;

import java.util.EnumSet;

import javax.servlet.DispatcherType;

import org.jsondoc.spring.boot.starter.EnableJSONDoc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.system.ApplicationPidFileWriter;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import com.alibaba.druid.support.http.StatViewServlet;
import com.joinway.framework.admin.core.servlet.UEditorServlet;

@SpringBootApplication
@ImportResource({"classpath:spring/applicationContext.xml", "classpath:spring/app-context.xml"})
//@EnableJSONDoc
public class PlatformAdmin implements SmartLifecycle {

	private final static Logger log = LoggerFactory.getLogger(PlatformAdmin.class);
	
	public final static String MODE_KEY = "app.mode";
	
	public final static String COMPACT_MODE = "compact";
	
	static boolean isCompactMode = false;
	
	@Bean public ServletRegistrationBean ueditorServletRegistration(){
		return new ServletRegistrationBean(new UEditorServlet(), "*.do");
	}
	
	@Bean public ServletRegistrationBean statViewServletRegistration(){
		return new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
	}
	
	@Bean public FilterRegistrationBean filterRegistrationBean () {
		FilterRegistrationBean bean = new FilterRegistrationBean();
		
		bean.setFilter(new CharacterEncodingFilter());
		bean.setDispatcherTypes(EnumSet.allOf(DispatcherType.class));
		bean.addUrlPatterns("/*");
		bean.addInitParameter("encoding", "UTF-8");
		bean.addInitParameter("forceEncoding", "true");
		
		return bean;
	}
	
	@Bean public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
	    ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet);
	    registration.addUrlMappings("*.json", "*.dox");
	    registration.setOrder(2);
	    
	    return registration;
	}
	
//	@Bean public ServletContextInitializer initializer() {
//	    return new ServletContextInitializer() {
//	        @Override
//	        public void onStartup(ServletContext servletContext) throws ServletException {
//	            servletContext.setInitParameter("contextInitializerClasses", "com.joinway.admin.platform.PlatformAdmin");
//	        }
//	    };
//	}
	
	public static void main(String[] args) throws Exception {
		String pidFile = args != null && args.length > 0 ? args[0] : null;
		String mode = args != null && args.length > 1 ? args[1] : COMPACT_MODE;
		
		if(COMPACT_MODE.equals(mode)){
			System.setProperty("db.type", "hsqldb");
			System.setProperty(MODE_KEY, mode);
			isCompactMode = true;
			HsqldbServer.start();
		}
		
		SpringApplication springApplication = new SpringApplication(PlatformAdmin.class);
//        ApplicationContext ctx = SpringApplication.run(Application.class, args);
		if(pidFile != null){
			springApplication.addListeners(new ApplicationPidFileWriter(pidFile));
			springApplication.addInitializers(new PlatformAdminProfileInitializer());
		}
//		System.getProperties().values().stream().forEach(v -> System.out.println(v));
		springApplication.run(args);
		
//        System.out.println(System.getProperty("user.home"));
//        System.out.println("Let's inspect the beans provided by Spring Boot:");
    }

	@Override
	public void start() {
	}

	@Override
	public void stop() {
		if(isCompactMode){
			HsqldbServer.stop();
		}
	}

	@Override
	public boolean isRunning() {
		return true;
	}

	@Override
	public int getPhase() {
		return 0;
	}

	@Override
	public boolean isAutoStartup() {
		return true;
	}

	@Override
	public void stop(Runnable callback) {
		stop();
		callback.run();
	}

//	@Override
//	public void initialize(ConfigurableWebApplicationContext ctx) {
//		if(isCompactMode){
//			log.info("reset current profile to [compact]");
//			ctx.getEnvironment().setActiveProfiles("compact");
//		}
//	}

//	@Override
//	public void onStartup(ServletContext servletContext) throws ServletException {
//		servletContext.setInitParameter("contextInitializerClasses", "com.joinway.admin.platform.PlatformAdmin");
//		super.onStartup(servletContext);
//	}

}
